// components/mud-composition/index.js
import {
  mudComposition
} from '../../dataSource'
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    show: {
      type: Boolean
    },
    value: {
      type: String,
      value: '',
      observer(data){
        this.fillData(data);
      }
    },
    readonly: {
      type: Boolean,
      value: true
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    source: [],
    total: 0
  },

  /**
   * 组件的方法列表
   */
  methods: {
    setDataSource() {
      const arr = Object.keys(mudComposition).map(it => {
        return {
          key: it,
          label: mudComposition[it],
          value: 0
        }
      })
      this.setData({
        source: arr
      })
    },
    /**
     * 返回数量
     * @param {Array} list 
     */
    getTotal(list) {
      return (list.reduce((curentVal, preVal) => {
        return curentVal + Number(preVal.value);
      }, 0)).toFixed(2)
    },
    onChange(event) {
      const {
        index
      } = event.currentTarget.dataset;
      const list = [...this.data.source];
      const value = event.detail;
      list[index].value = value;
      const total = this.getTotal(list);
      this.setData({
        source: list,
        total
      })
    },
    /**
     * 填充已有数据
     */
    fillData(data){
      const source = JSON.parse(data);
      const total = this.getTotal(source);
      this.setData({
        source,
        total
      })
    },
    /**
     * 表单数据传递
     */
    onSubmit(){
      const jsonStr = JSON.stringify(this.data.source);
      this.triggerEvent('change', jsonStr);
    },
    onClose(){
      this.triggerEvent('close');
    }
  },
  lifetimes: {
    attached() {
      // 在组件实例进入页面节点树时执行
      this.setDataSource();
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },

  }
})